package com.example.springboot.controller;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.springboot.entity.Res;
import com.example.springboot.entity.User;
import com.example.springboot.entity.UserEntity;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/account")
public class LoginController {
    private JwtUtil jwtUtil;
    @Autowired
    private UserService userService;
    private ObjectMapper mapper = new ObjectMapper();

    @PostMapping("/login")
    public Res<Map<String, String>> login(@RequestBody UserEntity user) {
        try {
//        验证账号密码

            boolean flag = userService.verify(user);
            if (!flag) {
                return new Res<Map<String, String>>().code(HttpStatus.UNAUTHORIZED.value()).msg("账号或密码错误");
            }
            User user2 =userService.getUserByUsername(user.getUsername());
            Map<String, String> payload = new HashMap<>();
            payload.put("userId", user2.getId().toString());
            payload.put("username", user.getUsername());

            //payload 中包含用户名:username和id
            String token = jwtUtil.getTokenRsa(payload);
            Map<String, String> response = new HashMap<>();

            response.put("token", token);
            String userInfoJson = mapper.writeValueAsString(userService.getUserInfo(token));
            response.put("userInfo", userInfoJson);
            return new Res<Map<String, String> >().code(HttpStatus.OK.value()).data(response);
        } catch (JsonProcessingException e) {
            return new Res<Map<String, String>>().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).msg("服务器内部错误");
        }
    }
    @PostMapping("/register")
    public Res<String> register(@RequestBody UserEntity user) {
        try {
            userService.insert(user);
            return new Res<String>().code(HttpStatus.OK.value());
        } catch (Exception e) {
            return new Res<String>().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).msg("服务器内部错误");
        }
    }

    @PostMapping("/refresh")
    public Res<Map<String, String>> loginWithToken(@RequestHeader("Authorization") String token) {
        try {
            String reqToken = token.substring(7);// 去掉 "Bearer " 前缀
            // 解析指定的token
            DecodedJWT decodedJWT = jwtUtil.decodeRsa(reqToken);
            // 获取解析后的token中的payload信息
//        Claim userId = decodedJWT.getClaim("userId");
            Claim userName = decodedJWT.getClaim("username");
            User user2 =userService.getUserByUsername(userName.asString());
            // 输出超时时间
            Map<String, String> payload = new HashMap<>();
            payload.put("userId", user2.getId().toString());
            payload.put("username", userName.asString());
            String resToken = jwtUtil.getTokenRsa(payload);
            Map<String, String> response = new HashMap<>();

            response.put("token", resToken);
            String userInfoJson = mapper.writeValueAsString(userService.getUserInfo(token));
            response.put("userInfo", userInfoJson);
            return new Res<Map<String, String>>().code(HttpStatus.OK.value()).data(response);
        } catch (Exception e) {
            System.out.println(e);
            return new Res<Map<String, String>>().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).msg("服务器内部错误");
        }
    }
}
